package pers.mihao.quickstream.common.util;


import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.UrlResource;
import pers.mihao.quickstream.common.exception.BaseException;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class HttpResponseUtil {

    private static volatile Map<String, String> CACHE = null;

    public static String getHttpResponseTypeByFileName(String fileName) {
        if (CACHE == null) {
            synchronized (HttpResponseUtil.class) {
                if (CACHE == null) {
                    parseConfig();
                }
            }
        }

        String suffix = FileUtil.getFileSuffix(fileName);
        String responseType = CACHE.get(suffix);
        if (responseType == null) {
            throw new BaseException("Not Support File Suffix " + suffix + " To Response");
        }
        return responseType;
    }

    private static void parseConfig() {
        Enumeration<URL> urls = null;
        try {
            urls = HttpResponseUtil.class.getClassLoader()
                    .getResources("META-INF/config/mime.json");
        } catch (IOException e) {
            throw new BaseException("Read File mime.json Error");
        }
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            try (InputStream inputStream = resource.getInputStream()) {
                JSONObject jsonObject = JSONObject.parseObject(inputStream, new Type() {
                    @Override
                    public String getTypeName() {
                        return JSONObject.class.getTypeName();
                    }
                });
                CACHE = new HashMap<>();
                for (String key : jsonObject.keySet()) {
                    String types = jsonObject.getString(key);
                    for (String type : types.split(",")) {
                        CACHE.put(type, key);
                    }
                }
            } catch (IOException e) {
                throw new BaseException(e);
            }
        }
    }


}
